package com.hsy.order.base.http

import java.util.Calendar
import java.util.concurrent.TimeUnit

import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import okhttp3.*

import com.flux.utils.GsonUtil
import com.hsy.order.base.Config

/**
 * 网络请求工具类
 * Created on 2017/12/4.
 *
 * @author Yang
 */
object RetrofitFactory {

    private const val CACHE_MAX_TIME = 12 * 60 * 60

    private var mOkHttpClient: OkHttpClient

    init {
        //设置缓存策略
        val interceptor = Interceptor { chain ->
            val request = chain.request()
            if (request.url().toString().startsWith(Config.API_SERVER)) {
                val response = chain.proceed(request)
                var maxTime = CACHE_MAX_TIME
                val receiveDate = response.headers().getDate("Date")
                if (null != receiveDate) {
                    //设置缓存的到期时候
                    val calendar = Calendar.getInstance()
                    calendar.time = receiveDate
                    val hour = calendar.get(Calendar.HOUR_OF_DAY)
                    val min = calendar.get(Calendar.MINUTE)

                    maxTime = 24 * 3600 - hour * 3600 - min * 60
                }
                response.newBuilder()
                        .header("Cache-Control", "max-age=$maxTime")
                        .build()
            } else chain.proceed(request)
        }

        mOkHttpClient = OkHttpClient.Builder()
                .retryOnConnectionFailure(true) //连接失败是否重连
                .connectTimeout(15, TimeUnit.SECONDS) //超时时间15s
                .addNetworkInterceptor(interceptor) //加入定义好的拦截器
                .addInterceptor(HttpInterceptor.setLevel(HttpInterceptor.Level.BODY))//log拦截器
                .build()
    }

    fun <T> getService(service: Class<T>): T {
        return Retrofit.Builder()
                .client(mOkHttpClient)
                .baseUrl(Config.API_SERVER)
                .addConverterFactory(GsonConverterFactory.create(GsonUtil.httpGson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())    //允许以 Observable 形式返回
                .build()
                .create(service)
    }
}